package homework;

// 求数组的最大值和次大值
public class F3 {

    public static void main(String[] args) {

        int[] data = {90, 4, 6, 8, 899};
        t1(data);
        t2(data);
    }

    public static void t1(int[] nums) {
        int max1 = nums[0];
        int max2 = nums[0];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > max1) {
                max2 = max1;
                max1 = nums[i];

            } else if (nums[i] > max2) {
                max2 = nums[i];
            }
        }


        System.out.println(max1);
        System.out.println(max2);
    }
    // 分治

    // 由于要返回两个数,所以定义一个类
    static class Res {
        int max1;
        int max2;

        @Override
        public String toString() {
            return "Res{" +
                    "max1=" + max1 +
                    ", max2=" + max2 +
                    '}';
        }
    }

    public static void t2(int[] nums) {
        System.out.println(solve(nums, 0, nums.length - 1));

    }

    private static Res solve(int[] nums, int left, int right) {
        Res res = new Res();
        if (left == right) {
            res.max1 = nums[left];
            res.max2 = -1;
        } else if (left == right - 1) {
            res.max1 = Math.max(nums[left], nums[right]);
            res.max2 = Math.min(nums[left], nums[right]);
        } else {
            int mid = (left + right) >> 1;
            Res r1 = solve(nums, left, mid);
            Res r2 = solve(nums, mid + 1, right);
            if (r1.max1 > r2.max1) {
                res.max1 = r1.max1;
                res.max2 = Math.max(r2.max1, r1.max2);
            } else {
                res.max1 = r2.max1;
                res.max2 = Math.max(r1.max1, r2.max2);
            }
        }
        return res;
    }
}
